package com.atguigu.demo.dao.impl;

import com.atguigu.demo.dao.BaseDao;
import com.atguigu.demo.dao.api.TigerDao;
import com.atguigu.demo.entity.Tiger;

import java.util.List;

public class TigerDaoImpl extends BaseDao implements TigerDao {
    @Override
    public List<Tiger> selectAllTigerList() {

        String sql = "select tiger_id tigerId, tiger_name tigerName, tiger_age tigerAge, tiger_salary tigerSalary from t_tiger";

        return selectList(sql, Tiger.class);
    }

    @Override
    public Tiger selectTigerById(String tigerId) {

        String sql = "select tiger_id tigerId, tiger_name tigerName, tiger_age tigerAge, tiger_salary tigerSalary from t_tiger where tiger_id=?";

        return selectOne(sql, Tiger.class, tigerId);
    }

    @Override
    public void deleteById(String tigerId) {
        String sql = "delete from t_tiger where tiger_id=?";
        commonUpdate(sql, tigerId);
    }

    @Override
    public void insertTiger(Tiger tiger) {
        String sql = "insert into t_tiger(tiger_name, tiger_age, tiger_salary) values(?,?,?)";
        commonUpdate(sql, tiger.getTigerName(), tiger.getTigerAge(), tiger.getTigerSalary());
    }

    @Override
    public void updateTiger(Tiger tiger) {
        String sql = "update t_tiger set tiger_name=?, tiger_age=?, tiger_salary=? where tiger_id=?";
        commonUpdate(sql, tiger.getTigerName(), tiger.getTigerAge(), tiger.getTigerSalary(), tiger.getTigerId());
    }

    @Override
    public Long selectCountByCondition(String tigerNameCondition) {

        // 1、拼接 SQL 语句
        String sql = "select count(*) from t_tiger" + getWhereClause(tigerNameCondition);

        // 2、执行 SQL 语句返回查询结果
        return selectSingleValue(sql);
    }

    /**
     * 把动态条件部分封装为一个专门的方法，需要使用的地方直接调方法即可适配两种情况
     * @param tigerNameCondition
     * @return
     */
    private String getWhereClause(String tigerNameCondition) {
        // ※重要提示：tigerNameCondition 不一定有值！！！所以必须适配两种情况
        // 1、声明一个局部变量，初始值设置为空字符串
        String whereClause = "";

        // 2、判断 tigerNameCondition 是否包含有效值
        if (tigerNameCondition != null && tigerNameCondition.trim().length() > 0) {
            // ❤注意点 1：where 左边要有一个空格
            // ❤注意点 2：%%两边要有引号，如果使用双引号就需要转义
            whereClause = " where tiger_name like '%" + tigerNameCondition + "%'";
        }
        return whereClause;
    }

    @Override
    public List<Tiger> selectTigerListByConditionLimit(Integer pageNum, Integer pageSizeInt, String tigerNameCondition) {

        String sql = "select tiger_id tigerId, tiger_name tigerName, tiger_age tigerAge, tiger_salary tigerSalary from t_tiger" + getWhereClause(tigerNameCondition) + " order by tiger_id desc limit ?,?";

        // pageNum 需要使用公式计算得到 index，再传入给 limit 子句
        return selectList(sql, Tiger.class, (pageNum - 1) * pageSizeInt, pageSizeInt);
    }
}
